<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        v-model="form"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="menuLeft">
          <el-button type="primary" @click="handleAdd" size="small">新 增</el-button>
        </template>
        <template slot="nums" slot-scope="scope">
          <el-input
            v-if="scope.row.numsEdit == true"
            v-model="scope.row.nums"
            @blur="submitNums(scope.row.nums)"
            @keyup.enter.native="submitNums(scope.row.nums)"
          ></el-input>
          <div v-else>
            <span>{{scope.row.nums}}</span>
            <el-button type="text" @click="editNums(scope.row)">
              <i class="el-icon-edit"></i>
            </el-button>
          </div>
        </template>
        <template slot="isPublish" slot-scope="scope">
          <el-tag type="info" v-if="scope.row.isPublish === 0">未加入</el-tag>
          <el-tag v-if="scope.row.isPublish === 1">已加入</el-tag>
          <el-tag v-if="scope.row.isPublish === 2">已停用</el-tag>
        </template>
        <template slot="type" slot-scope="scope">
          <el-tag v-if="scope.row.type==0">满减券</el-tag>
        </template>
        <template slot="isExpiration" slot-scope="scope">
          <el-tag v-if="scope.row.isExpiration == 0">未到期</el-tag>
          <el-tag type="info" v-if="scope.row.isExpiration == 1">已到期</el-tag>
          <el-button
            v-if="scope.row.isExpiration !== 1 && scope.row.isPublish != 0"
            type="text"
            size="small"
            plain
            :style="scope.row.isExpiration== 0?'color:#999999':''"
            @click="handleExpirationChange(scope.row,scope.index)"
          >{{scope.row.isPublish == 1?'停用':'启用'}}</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            icon="el-icon-check"
            size="small"
            plain
            @click="handleCouponDetail(scope.row,scope.index)"
          >查看</el-button>
          <el-button
            type="text"
            icon="el-icon-check"
            size="small"
            plain
            v-if="scope.row.isPublish == 0"
            @click="handleEdit(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            icon="el-icon-check"
            size="small"
            plain
            @click="handleCouponDel(scope.row,scope.index)"
          >删除</el-button>
        </template>
        <template slot="useDateRangeForm" slot-scope="scope">
          <el-date-picker
            v-model="form.useDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </template>
        <template slot="shopIdForm" slot-scope="scope">
          <el-select v-model="form.shopId" placeholder="请选择" @change="handlerShopChange">
            <el-option
              v-for="item in merList"
              :key="item.id"
              :label="item.shopName"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template slot="couponTypeForm" slot-scope="scope">
          <el-radio-group v-model="couponType">
            <el-radio
              v-for="(item, index) in couponTypeList"
              :label="Number(item.value)"
              :key="index"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </template>
        <template slot="valueForm" slot-scope="scope">
          <el-select v-model="form.value" placeholder="请选择">
            <el-option v-for="item in typesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </template>
      </avue-crud>
      <el-dialog title="优惠券详情" :visible.sync="dialogVisible" width="40%">
        <div>
          <el-form ref="form" :model="form" label-position="left" inline class="demo-table-expand">
            <el-form-item label="名称:">
              <span>{{couponDetail.name}}</span>
            </el-form-item>
            <el-form-item label="优惠金额:">
              <span>{{couponDetail.money}}元</span>
            </el-form-item>
            <el-form-item label="最低消费金额:">
              <span>{{couponDetail.minConsum}}元</span>
            </el-form-item>
            <el-form-item label="是否加入领券中心:">
              <span v-if="couponDetail.isPublish==1">是</span>
              <span v-else>否</span>
            </el-form-item>
            <el-form-item label="发行数量:">
              <span>{{couponDetail.nums}}张</span>
            </el-form-item>
            <el-form-item label="剩余数量:">
              <span>{{couponDetail.surplus}}张</span>
            </el-form-item>
            <el-form-item label="商铺名称：">
              <span>{{couponDetail.shopName}}</span>
            </el-form-item>
            <el-form-item label="服务类目:">
              <span>{{couponDetail.valueName}}</span>
            </el-form-item>
            <el-form-item label="可用起始日期:">
              <span>{{couponDetail.useStartDate}}</span>
            </el-form-item>
            <el-form-item label="可用截止日期:">
              <span>{{couponDetail.useEndDate}}</span>
            </el-form-item>
            <el-form-item label="是否到期:">
              <span v-if="couponDetail.isExpiration==1">已到期</span>
              <span v-else>未到期</span>
            </el-form-item>
            <el-form-item label="优惠券类型:">
              <span v-if="couponDetail.type==0">满减券</span>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  editCouponNum,
  editCouponIsExp
} from "@/api/marketing/coupon";
import { getAllShops } from "@/api/shop/shops";
import { tableOption } from "@/const/crud/marketing/coupon";
import { getMerTypeByShopId } from "@/api/shop/shopservicestype";
export default {
  name: "coupon",
  data() {
    return {
      couponDetail: {},
      dialogVisible: false,
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      form: {
        value: "",
        shopId: "",
        useDateRange: [],
        couponType: 0
      },
      couponType: 0,
      merList: [],
      typesList: [],
      couponTypeList: [],
      editIdx: null
    };
  },
  mounted: function() {
    this.getServicesTypeListByDictType();
    this.getList(this.page);
  },
  // computed: {
  //   ...mapGetters(['permissions'])
  // },
  watch: {
    couponType() {
      this.form.couponType = this.couponType;
    }
  },
  methods: {
    // 获取字典中优惠券类型列表
    getServicesTypeListByDictType() {
      this.$http({
        url: this.$http.adornUrl("/sys/dict/type/coupon_type"),
        method: "get"
      }).then(res => {
        this.couponTypeList = res.data.data;
        if (this.couponTypeList && this.couponTypeList.length > 0) {
          this.form.couponType = String(this.couponTypeList[0].value);
        }
      });
    },

    // 获取门店列表
    getMerList() {
      const data = new FormData();
      data.append("shopId", this.$store.state.user.shopId);
      getAllShops(data).then(res => {
        this.merList = res.data.data;
        if (this.merList && this.merList.length > 0) {
          let data = new FormData();
          data.append("shopId", this.merList[0].id);
          getMerTypeByShopId(data).then(res => {
            this.typesList = res.data.data;
          });
        }
      });
    },

    // 获取优惠券列表
    getList(page, params) {
      this.tableLoading = true;
      fetchList(Object.assign({
            shopId: this.$store.state.user.shopId,
            current: page.currentPage,
            size: page.pageSize
          },params)
      ).then(response => {
        console.log('获取优惠券列表',response)
        this.tableData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    /**
     * @title 打开新增窗口
     * @detail 调用crud的handleadd方法即可
     *
     **/
    handleAdd: function() {
      this.form.value = "";
      //获取门店列表
      this.getMerList();
      this.$refs.crud.rowAdd();
    },
    handleEdit(row, index) {
      if (row.useStartDate && row.useEndDate) {
        row.useDateRange = [row.useStartDate, row.useEndDate];
      }
      //获取门店列表
      this.getMerList();
      this.couponType = row.type;
      this.$refs.crud.rowEdit(row, index);
    },

    // 删除提示弹窗
    handleDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },

    // 删除优惠券
    rowDel: function(row, index) {
      var _this = this;
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          _this.tableData.splice(index, 1);
          _this.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          this.getList(this.page);
        })
        .catch(function(err) {});
    },

    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate: function(row, index, done) {
      let useDateRange = row.useDateRange;
      if (useDateRange) {
        row.userStartDateLong = new Date(useDateRange[0]).getTime();
        row.useEndDateLong = new Date(useDateRange[1]).getTime();
      }
      row.type = this.couponType;
      putObj(row).then(data => {
        this.tableData.splice(index, 1, Object.assign({}, row));
        this.$message({
          showClose: true,
          message: "修改成功",
          type: "success"
        });
        done();
        this.getList(this.page);
      });
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave: function(row, done) {
      let useDateRange = row.useDateRange;
      if (useDateRange) {
        row.userStartDateLong = new Date(useDateRange[0]).getTime();
        row.useEndDateLong = new Date(useDateRange[1]).getTime();
      }
      row.type = this.couponType;
      if (this.$store.state.user.shopId) {
        row.shopId = this.$store.state.user.shopId;
      }
      addObj(row).then(data => {
        this.tableData.push(Object.assign({}, row));
        this.$message({
          showClose: true,
          message: "添加成功",
          type: "success"
        });
        done();
        this.getList(this.page);
      });
    },
    /**
     * 刷新回调
     */
    refreshChange() {
      this.getList(this.page);
    },

    handleCouponDel(row, index) {
      this.$http({
        url: this.$http.adornUrl("/marketing/coupon/delCoupon"),
        method: "post",
        params: {
          id: row.id
        }
      }).then(res => {
        this.getList(this.page);
      });
    },
    //优惠券查看
    handleCouponDetail(row, index) {
      this.dialogVisible = true;
      if (row.useStartDate && row.useEndDate) {
        row.useDateRange = [row.useStartDate, row.useEndDate];
      }
      //获取门店列表
      this.getMerList();
      // this.getMerTypes()
      this.form.couponType = String(row.type);
      this.couponDetail = row;
    },
    handlerShopChange(val) {
      this.typesList = [];
      this.form.value = "";
      let data = new FormData();
      data.append("shopId", val);
      getMerTypeByShopId(data).then(res => {
        this.typesList = res.data.data;
      });
    },
    currentChange(val) {
      this.page.currentPage = val;
      this.getList(this.page);
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getList(this.page);
    },

    // 修改优惠券数量
    editNums(row) {
      if (this.editIdx !== null) {
        this.$set(this.tableData[this.editIdx], "numsEdit", false);
      }
      this.editIdx = row.$index;
      this.$set(row, "numsEdit", true);
    },

    submitNums(nums) {
      if (this.tableData[this.editIdx].numsEdit) {
        let data = new FormData();
        data.append("id", this.tableData[this.editIdx].id);
        data.append("num", nums);
        editCouponNum(data).then(res => {
          if (res.data.code == 0) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.getList(this.page);
          } else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error"
            });
          }
        });
      }
    },

    // 是否启用优惠券
    handleExpirationChange(row) {
      if (row.isPublish == 1){
        let data = new FormData();
        data.append("id", row.id);
        data.append("exp", 2);
        editCouponIsExp(data).then(res => {
          console.log(res)
          console.log(row.isPublish)
          if (res.data.code == 0) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.getList(this.page);
          } else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error"
            });
          }
        });
      }else{
        let data = new FormData();
        data.append("id", row.id);
        data.append("exp", 1);
        editCouponIsExp(data).then(res => {
          console.log(res)
          console.log(row.isPublish)
          if (res.data.code == 0) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.getList(this.page);
          } else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error"
            });
          }
        });
      }

    }
  }
};
</script>

<style lang="scss" scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
